/**
 * Created by xiey on 2016/3/29.
 */
as.directive('dateField', [function () {
    return {
        restrict  : 'EA',
        scope     : {
            fieldConfig: '<'
        },
        require   : {
            ngModel: '^^ngModel',
            field  : '^^aField'
        },
        template  : function () {
            var content = [];
            content.push('<p class="input-group input-group-sm">');
            content.push('  <input ng-model="model" ng-change="change()" a-datepicker-popup="{{format}}" datepicker-options="dateOptions" is-open="open" class="form-control" type="text" readonly="readonly"/>');
            content.push('  <span class="input-group-btn">');
            content.push('    <button type="button" class="btn btn-default" ng-click="open=!open"><i class="glyphicon glyphicon-calendar"></i></button>');
            content.push('  </span>');
            content.push('</p>');
            return content.join('');
        },
        link      : function (scope, el, attr, req) {
            req.ngModel.$render = function () {
                scope.model = req.ngModel.$modelValue || req.ngModel.$viewValue
            };
            scope.change = function () {
                req.ngModel.$setViewValue(scope.model);
            };
        },
        controller: ['$scope', '$attrs', function ($scope, $attrs) {
            var type = $attrs.ngSwitchWhen;
            var FORMAT = {
                date : 'yyyy-MM-dd',
                month: 'yyyy-MM',
                year : 'yyyy'
            };
            var mode = type === 'date' ? 'day' : type;
            $scope.format = $scope.fieldConfig.format || FORMAT[type];
            // 在 link 中配置会失效
            $scope.dateOptions = angular.extend({}, $scope.fieldConfig, {
                showWeeks     : false,
                startingDay   : 1,
                datepickerMode: mode,
                minMode       : mode
            });
        }]
    };
}]);